package com.jie.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author jie
 * @version 1.0 2025-02-14
 */
@Slf4j
public class ApiRestrictUtil {

    private final AtomicInteger count = new AtomicInteger(0);
    private final AtomicLong lastResetTime = new AtomicLong(System.currentTimeMillis());

    private final int maxRequestsPerSecond;

    public ApiRestrictUtil(int maxRequestsPerSecond) {
        this.maxRequestsPerSecond = maxRequestsPerSecond;
    }

    public synchronized boolean onRequest() {
        long currentTime = System.currentTimeMillis();
        long differenceValue = 1000;
        if (currentTime - lastResetTime.get() >= differenceValue) {
            count.set(0);
            lastResetTime.set(currentTime);
        }

        if (count.incrementAndGet() > maxRequestsPerSecond) {
            log.warn("请求超过每秒{}次限制",maxRequestsPerSecond);
            count.set(0);
            lastResetTime.set(System.currentTimeMillis());
            return true;
        }
        return false;
    }
}
